import api from '@/utils/api'

const state = {
  conversationList: [],
  currentConversation: null,
  messageList: [],
  unreadCount: 0,
  isConnected: false,
  socket: null
}

const mutations = {
  SET_CONVERSATION_LIST(state, conversationList) {
    state.conversationList = conversationList
  },
  
  SET_CURRENT_CONVERSATION(state, conversation) {
    state.currentConversation = conversation
  },
  
  SET_MESSAGE_LIST(state, { messages, isRefresh = false }) {
    if (isRefresh) {
      state.messageList = messages
    } else {
      state.messageList = [...messages, ...state.messageList]
    }
  },
  
  ADD_MESSAGE(state, message) {
    state.messageList.push(message)
  },
  
  UPDATE_MESSAGE(state, { messageId, updates }) {
    const index = state.messageList.findIndex(msg => msg.messageId === messageId)
    if (index !== -1) {
      state.messageList.splice(index, 1, { ...state.messageList[index], ...updates })
    }
  },
  
  SET_UNREAD_COUNT(state, count) {
    state.unreadCount = count
    // 同步更新TabBar徽章
    if (count > 0) {
      uni.setTabBarBadge({
        index: 2, // 消息Tab的索引
        text: count > 99 ? '99+' : count.toString()
      })
    } else {
      uni.removeTabBarBadge({
        index: 2
      })
    }
  },
  
  SET_CONNECTION_STATUS(state, status) {
    state.isConnected = status
  },
  
  SET_SOCKET(state, socket) {
    state.socket = socket
  },
  
  CLEAR_MESSAGES(state) {
    state.messageList = []
  }
}

const actions = {
  // 获取会话列表
  async getConversationList({ commit }) {
    try {
      const response = await api.get('/chat/conversations')
      commit('SET_CONVERSATION_LIST', response.data)
      
      // 计算总未读数
      const totalUnread = response.data.reduce((sum, conv) => sum + (conv.unreadCount || 0), 0)
      commit('SET_UNREAD_COUNT', totalUnread)
      
      return response
    } catch (error) {
      throw error
    }
  },
  
  // 获取聊天记录
  async getMessageList({ commit, state }, { conversationId, page = 1, isRefresh = false }) {
    try {
      const response = await api.get(`/chat/messages/${conversationId}`, {
        params: { page, size: 20 }
      })
      
      commit('SET_MESSAGE_LIST', { 
        messages: response.data.reverse(), // 消息按时间倒序排列
        isRefresh 
      })
      
      return response
    } catch (error) {
      throw error
    }
  },
  
  // 发送消息
  async sendMessage({ commit, state }, messageData) {
    try {
      const response = await api.post('/chat/message', messageData)
      
      // 添加到本地消息列表
      commit('ADD_MESSAGE', response.data)
      
      // 通过WebSocket发送消息
      if (state.socket && state.isConnected) {
        state.socket.send(JSON.stringify({
          type: 'message',
          data: response.data
        }))
      }
      
      return response
    } catch (error) {
      throw error
    }
  },
  
  // 标记消息已读
  async markAsRead({ commit }, messageId) {
    try {
      const response = await api.put(`/chat/message/${messageId}/read`)
      commit('UPDATE_MESSAGE', { 
        messageId, 
        updates: { isRead: true } 
      })
      return response
    } catch (error) {
      throw error
    }
  },
  
  // 撤回消息
  async recallMessage({ commit }, messageId) {
    try {
      const response = await api.put(`/chat/message/${messageId}/recall`)
      commit('UPDATE_MESSAGE', { 
        messageId, 
        updates: { isRecalled: true } 
      })
      return response
    } catch (error) {
      throw error
    }
  },
  
  // 连接WebSocket
  connectWebSocket({ commit, state, rootGetters }) {
    const token = rootGetters['user/token']
    if (!token) return
    
    const socketUrl = `ws://localhost:8080/websocket/chat/${token}`
    
    const socket = uni.connectSocket({
      url: socketUrl,
      success() {
        console.log('WebSocket连接成功')
      }
    })
    
    socket.onOpen(() => {
      console.log('WebSocket连接已打开')
      commit('SET_CONNECTION_STATUS', true)
      commit('SET_SOCKET', socket)
    })
    
    socket.onMessage((event) => {
      try {
        const data = JSON.parse(event.data)
        if (data.type === 'message') {
          commit('ADD_MESSAGE', data.data)
        }
      } catch (error) {
        console.error('解析WebSocket消息失败:', error)
      }
    })
    
    socket.onClose(() => {
      console.log('WebSocket连接已关闭')
      commit('SET_CONNECTION_STATUS', false)
      commit('SET_SOCKET', null)
    })
    
    socket.onError((error) => {
      console.error('WebSocket连接错误:', error)
      commit('SET_CONNECTION_STATUS', false)
    })
  },
  
  // 断开WebSocket
  disconnectWebSocket({ commit, state }) {
    if (state.socket) {
      state.socket.close()
      commit('SET_CONNECTION_STATUS', false)
      commit('SET_SOCKET', null)
    }
  },
  
  // 创建会话
  async createConversation({ commit }, conversationData) {
    try {
      const response = await api.post('/chat/conversation', conversationData)
      return response
    } catch (error) {
      throw error
    }
  }
}

const getters = {
  conversationList: state => state.conversationList,
  currentConversation: state => state.currentConversation,
  messageList: state => state.messageList,
  unreadCount: state => state.unreadCount,
  isConnected: state => state.isConnected
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}